package com.example.web.servlet;

import com.example.common.Result;
import com.example.model.Trip;
import com.example.service.TripService;
import com.example.service.impl.TripServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@WebServlet("/addTrip")
public class TripAddServlet extends HttpServlet {
    private TripService tripService = new TripServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        if (parameterMap.isEmpty()) {
            //获取参数失败 . 返回错误消息
            Result result = Result.fail(400, "请输入正确的车次信息");
            String result_str = objectMapper.writeValueAsString(result);
            System.out.println(result_str);
            resp.getWriter().write(result_str);
            return;
        }
        Trip trip = new Trip();

        try {
            BeanUtils.populate(trip,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        boolean flag = tripService.addTrip(trip);
        if (flag) {
            // 添加成功
            Result result = Result.success("添加车次成功");
            String result_str = objectMapper.writeValueAsString(result);
            System.out.println(result_str);
            resp.getWriter().write(result_str);
            return;
        } else {
            // 添加失败
            Result result = Result.fail(400, "添加车次失败");
            String result_str = objectMapper.writeValueAsString(result);
            System.out.println(result_str);
            resp.getWriter().write(result_str);
            return;
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
